<?php
namespace app\common\model;
use think\Request;

/**
 * 餐桌/包间模型
 */
class Table extends BaseModel
{
    protected $name = 'table';
	protected $append = ['code','status'];
	
	/**
     * 二维码
     */
    public function getCodeAttr($value, $data)
    {
        return web_url().'assets/qrcode/table/'.$data['table_id'].'.png';
    }

	/**
     * 关联门店
     */
    public function shop()
    {
        return $this->hasOne('Shop', 'shop_id', 'shop_id');
    }
	
    /**
     * 状态
     */
    public function getStatusAttr($value,$data)
    {
        $status = [10 => '空闲', 20 => '忙碌', 30 => '预定'];
        $order_id = '';
        $pay_price = '';
        $time = '';
        if($order = Order::getOrderWhere(['table_id'=>$data['table_id'],'order_status'=>10])){
            $value = 20;
            $order_id = $order['order_id'];
            $pay_price = $order['pay_price'];
            $time = round((time() - strtotime($order['create_time']))/60);
        }
        return [
            'text' => $status[$value], 
            'value' => $value, 
            'order_id' => $order_id, 
            'time' => $time,
            'pay_price' => $pay_price
        ];
    }

    /**
     * 获取列表
     */
    public function getList($dataType='',$shop_id='',$search='')
    {
		//筛选条件
        $filter = [];
        !empty($shop_id) && $filter['shop_id'] = $shop_id;
        !empty($search) && $filter['table_name'] = $search;
        // 执行查询
        $tablelist = $this->with(['shop'])
            ->where($filter)
            ->order(['sort','table_id' => 'desc'])
            ->select();
        if(empty($dataType)){
            $list = $tablelist;
        }else{
            $list = [];
            for($n=0;$n<sizeof($tablelist);$n++){
                if($tablelist[$n]['status']['value'] == $dataType){
                    array_push($list,$tablelist[$n]);
                }
            }
        }
        return $list;
    }

    /**
     * 获取详情
     */
    public static function detail($table_id)
    {
        return self::get($table_id, ['shop']);
    }
}
